package mq

import (
	"context"
	"fmt"

	"bilinadmin/internal/service"

	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"

	pb "bilinadmin/api/pb/server"
	"bilinadmin/pkg/mq"
)

const (
	// 仓库更新
	InventoryUpdate = "inventory-update"
	// 品牌门店创建
	BrandStoreCreate = "bilinadmin-brand_store_create"
)

type mqHandler struct {
	*MqBase
	name string
}

// NewMqHandler new mq handler
func NewMqHandler() *mqHandler {
	return &mqHandler{
		MqBase: base,
		name:   "nsq_handler",
	}
}

// Register 注册消息
func (m *mqHandler) Register(c *mq.NsqConsumer) {
	if err := c.Register("bilinadmin-say_hello", "test", m.wrap("bilinadmin-say_hello", m.sayHello), 1); err != nil {
		m.logger.Bg().Panic("nsq topic: bilinadmin-say_hello", zap.Error(err))
	}
	if err := c.Register(InventoryUpdate, "bilinadmin", m.wrap(InventoryUpdate, m.inventoryUpdate), 5); err != nil {
		m.logger.Bg().Panic("nsq topic: inventory-update", zap.Error(err))
	}
	if err := c.Register(BrandStoreCreate, "bilinadmin", m.wrap(BrandStoreCreate, m.brandStoreCreate), 5); err != nil {
		m.logger.Bg().Panic("nsq topic: inventory-update", zap.Error(err))
	}
}

// test hello
func (m *mqHandler) sayHello(ctx context.Context, msg *nsq.Message) error {
	req := &pb.HelloRequest{}
	if errL := m.ParseBody(msg.Body, req); errL != nil {
		return errL
	}
	if req.Id == -1 {
		panic("panic test3")
	}
	m.logger.For(ctx).Info(fmt.Sprintf("Hello %s", req.Name))
	return nil
}

func (m *mqHandler) inventoryUpdate(ctx context.Context, msg *nsq.Message) error {
	req := &pb.WarehouseUpdateMessage{}
	if errL := m.ParseBody(msg.Body, req); errL != nil {
		return errL
	}
	return service.GetBrandService().CreateOrUpdateInventory(ctx, req)
}

func (m *mqHandler) brandStoreCreate(ctx context.Context, msg *nsq.Message) error {
	req := &pb.BrandStoreCreateMessage{}
	if errL := m.ParseBody(msg.Body, req); errL != nil {
		return errL
	}
	return service.GetRolePermissionSrv().CreateDefaultRoles(ctx, req.BrandId, req.StoreId)
}
